package com.avic.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.avic.gateway.common.util.lang.BaseResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

/**
 * 过滤错误的请求，封装response body错误格式
 *
 * @author: huangsheng
 * @date: 2018/8/24
 */
@Slf4j
public class FailedRequestPostFilter extends AbstractZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return shouldFilter(FailedRequestPostFilter.class.getSimpleName());
    }

    @Override
    public Object run() {

        RequestContext requestContext = RequestContext.getCurrentContext();
        String serviceApi = requestContext.getResponseBody();

        // 校验登入是否成功，成功则生产Token返回
        if (StringUtils.isNotBlank(serviceApi)) {
            JSONObject object = JSONObject.parseObject(serviceApi);
            if (object.containsKey(BaseResponse.SUCCESS_NAME) && object.getBoolean(BaseResponse.SUCCESS_NAME) == false) {
                log.info("URI request fail {}", requestContext.getRequest().getRequestURI());
                BaseResponse baseResponse = new BaseResponse();
                baseResponse.setSuccess(false);
                baseResponse.setCode(object.getString(BaseResponse.CODE_NAME));
                baseResponse.setMessage(object.getString(BaseResponse.MESSAGE_NAME));

                try {
                    requestContext.setResponseBody(objectMapper.writeValueAsString(baseResponse));
                } catch (JsonProcessingException e) {
                    log.warn("objectMapper writeValueAsString error {}", e.getMessage());
                    requestContext.setResponseBody(JSONObject.toJSONString(baseResponse));
                }
            }
        }
        return null;
    }

}
